/**
 * 
 */
package com.wzl.qs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;

/**
 * @author Li Xiaohui
 * 
 */
public class TakePhoto extends Activity implements Callback {

	public static boolean hasTaken = false;

	private Camera camera;
	private boolean isPreviewRunning = false;

	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;
	private Uri target = Media.EXTERNAL_CONTENT_URI;
	private int THUMBER_WIDTH = 200;
	private int THUMBER_HEIGHT = 150;
	String currentPhotoFile = null;
	String thunmberFile = null;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		Log.e(getClass().getSimpleName(), "onCreate");
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		setContentView(R.layout.pic);
		surfaceView = (SurfaceView) findViewById(R.id.SurfaceView01);
		surfaceHolder = surfaceView.getHolder();

		// set file name
		Intent intent = getIntent();
		Bundle data = intent.getExtras();
		this.currentPhotoFile = data.getString("fileName");
		this.thunmberFile = data.getString("thumber");
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		MenuItem item = menu.add(0, 0, 0, "goto gallery");
		item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Intent intent = new Intent(Intent.ACTION_VIEW, target);
				startActivity(intent);
				return true;
			}
		});
		return true;
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	Camera.PictureCallback mPictureCallbackJpeg = new Camera.PictureCallback() {
		public void onPictureTaken(byte[] data, Camera c) {
			Log.e(getClass().getSimpleName(), "PICTURE CALLBACK RAW: " + data);

			try {
				FileOutputStream file = new FileOutputStream(new File(
						currentPhotoFile));
				file.write(data);
				file.flush();
				file.close();

				// create thumbernail picture
				Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				int width = bitmapOrg.getWidth();
				int height = bitmapOrg.getHeight();
				// calculate the scale - in this case = 0.4f
				float scaleWidth = ((float) THUMBER_WIDTH) / width;
				float scaleHeight = ((float) THUMBER_HEIGHT) / height;
				// createa matrix for the manipulation
				Matrix matrix = new Matrix();
				// resize the bit map
				matrix.postScale(scaleWidth, scaleHeight);
				// recreate the new Bitmap
				Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
						width, height, matrix, true);
				FileOutputStream thumberNail = new FileOutputStream(new File(
						thunmberFile));
				resizedBitmap.compress(CompressFormat.JPEG, 100, thumberNail);
				resizedBitmap.recycle();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() {
		public void onShutter() {
			Log.e(getClass().getSimpleName(), "SHUTTER CALLBACK");
			// Set params in shuterCallback
			Camera.Parameters params = camera.getParameters();
			params.setPictureFormat(PixelFormat.JPEG);
			// param
			// params.setPreviewSize(PHOTO_WIDTH, PHOTO_HEIGHT);
			// params.setPictureSize(PHOTO_WIDTH, PHOTO_HEIGHT);
			camera.setParameters(params);

		}
	};

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			intent.putExtra("fileName", currentPhotoFile);
			setResult(1, intent);
			finish();
			return super.onKeyDown(keyCode, event);
		}

		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			camera.takePicture(mShutterCallback, null, mPictureCallbackJpeg);
			hasTaken = true;
			// finish();
			return true;
		}

		return false;
	}

	protected void onResume() {
		Log.e(getClass().getSimpleName(), "onResume");
		super.onResume();
	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	protected void onStop() {
		Log.e(getClass().getSimpleName(), "onStop");
		super.onStop();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.e(getClass().getSimpleName(), "surfaceCreated");
		camera = Camera.open();
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		Log.e(getClass().getSimpleName(), "surfaceChanged");
		if (isPreviewRunning) {
			camera.stopPreview();
		}
		// Camera.Parameters parameters = camera.getParameters();
		// parameters.setPictureFormat(PixelFormat.JPEG);
		// parameters.setPreviewSize(w, h);
		// camera.setParameters(parameters);

		try {
			camera.setPreviewDisplay(holder);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		camera.startPreview();
		isPreviewRunning = true;
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.e(getClass().getSimpleName(), "surfaceDestroyed");
		camera.stopPreview();
		isPreviewRunning = false;
		camera.release();
	}
}
